<template>
  <!-- 项目的最外层 -->
  <div class="outer">
    <!-- 窗口侧边栏 -->
    <div class="toolbar toolbar-wrap">
      <div class="content"></div>
      <div class="but list"></div>
      <div class="toolist">
        <div class="pull">
          <i class="tab-ico vip"></i>
          <em class="tab-text">商品会员</em>
        </div>
        <div class="pull">
          <i class="tab-ico cart"></i>
          <em class="tab-text">购物车</em>
        </div>
        <div class="pull">
          <i class="tab-ico follow"></i>
          <em class="tab-text">我的关注</em>
        </div>
        <div class="pull">
          <i class="tab-ico history"></i>
          <em class="tab-text">我的足迹</em>
        </div>
        <div class="pull">
          <i class="tab-ico message"></i>
          <em class="tab-text">我的消息</em>
        </div>
        <div class="pull">
          <i class="tab-ico jimi"></i>
          <em class="tab-text">咨询</em>
        </div>
      </div>
      <div class="back pull">
        <i class="tab-ico top"></i>
        <em class="tab-text">顶部</em>
      </div>
    </div>
    <!-- 头部 -->

    <!-- 商品分类导航 -->
    <div class="typeNav">
      <div class="container">
        <h2 class="all">全部商品分类</h2>
        <nav class="nav">
          <a href="###">服装城</a>
          <a href="###">美妆馆</a>
          <a href="###">尚品汇超市</a>
          <a href="###">全球购</a>
          <a href="###">闪购</a>
          <a href="###">团购</a>
          <a href="###">有趣</a>
          <a href="###">秒杀</a>
        </nav>
      </div>
    </div>

    <!-- 购物车列表 -->
    <div class="cart">
      <h4>全部商品</h4>
      <div class="cart-main">
        <div class="cart-th">
          <div class="cart-th1">全部</div>
          <div class="cart-th2">商品</div>
          <div class="cart-th4">数量</div>
          <div class="cart-th5">操作</div>
          <div class="cart-th6">小计（元）</div>
        </div>
        <div class="cart-body">
          <ul class="cart-list" v-for="c1 in cartInfoList" :key="c1.id">
            <li class="cart-list-con1">
              <input
                type="checkbox"
                name="chk_list"
                :checked="c1.isChecked"
                @click="updateChecked(c1)"
              />
            </li>
            <li class="cart-list-con2">
              <img :src="c1.imgUrl" />
              <div class="item-msg">
                {{ c1.skuName }}
              </div>
            </li>
            <li class="cart-list-con4">
              <span class="price">{{ c1.skuNum }}</span>
            </li>
            <li class="cart-list-con5">
              <a
                href="javascript:void(0)"
                class="mins"
                @click="modifyNum('jian', c1)"
                >-</a
              >
              <input
                autocomplete="off"
                type="text"
                :value="c1.skuNum"
                minnum="1"
                class="itxt"
                @change="modifyNum('gai', c1, $event)"
              />
              <a
                href="javascript:void(0)"
                class="plus"
                @click="modifyNum('jia', c1)"
                >+</a
              >
            </li>
            <li class="cart-list-con6">
              <span class="sum">{{ c1.skuPrice * c1.skuNum }}.00</span>
            </li>
            <li class="cart-list-con7">
              <a
                href="javascript:;"
                class="sindelet"
                @click="deleteSingle(c1.skuId)"
                >删除</a
              >
              <br />
              <a href="javascript:;">移到收藏</a>
            </li>
          </ul>
        </div>
      </div>
      <div class="cart-tool">
        <div class="select-all">
          <input class="chooseAll" type="checkbox" v-model="checkAll" />
          <span>全选</span>
        </div>
        <div class="option">
          <a href="javascript:;" @click="batchDelete">删除选中的商品</a>
          <a href="javascript:;">移到我的关注</a>
          <a href="javascript:;">清除下柜商品</a>
        </div>
        <div class="money-box">
          <div class="chosed">
            已选择 <span>{{ totalNo }}</span
            >件商品
          </div>
          <div class="sumprice">
            <em>总价（不含运费） ：</em>
            <i class="summoney">{{ totalPrice }}</i>
          </div>
          <div class="sumbtn">
            <router-link class="sum-btn" to="/trade">结算</router-link>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部 -->
    <Dialog :visible.sync="visible">
      <template v-slot:header>
        <p>提示</p>
      </template>
      <template>
        <p>您真的确定要删除{{ isDelOne ? "此项" : "所选择的" }}商品吗？</p>
      </template>
      <template #footer>
        <div class="btn-footer">
          <button class="btn btn-cancle" @click="visible = false">取消</button>
          <button class="btn btn-primary" @click="delShopCartInfo">确定</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqGetCartList,
  reqAddUpdateCart,
  checkDeleteCart,
  reqUpdateIsChecked,
  reqBatchDelete,
  updateCheckedAll,
} from "@/api";
import { skuNumReg } from "@/utils/reg";
import Dialog from "@/components/Dialog";
/* 
数据不会重复使用，可以不用写到vx内,基本数据渲染

关于数量操作，减少，增多，以及输入框修改，通过传入的参数来确定是哪一个操作，每一次操作都需要发送请求更改数据
修改数量携带参数，请求参数，id，skuNum(正数表示添加，负数表示减少)
不能超过200以及低于1，超出设置原值，符合要求才发送请求

单个删除，通过id删除，删除之后需要刷新页面，可以通过id直接过滤掉之前删除的数据，少发送一次请求

修改状态，1为true，0为false，每次选中都需要发送请求，携带参数id，isChecked
状态为数值不能直接取反，可以使用减法运算符

总数：当前对象数量*价格*是否被选中，不被选中计算结果为0

全选，使用计算属性，v-model监听，当被访问会执行get，被修改执行set，一开始需要先判断是否是全选，使用every必须所有都符合要求才选中
如果有一个不为1则不选中，如果购物车没有数据也为不选中

修改的话set可以拿到最新的值，根据值来判断获取到状态，根据新值遍历赋值，请求参数 id数组和状态
*/
export default {
  name: "cart",
  data() {
    return {
      cartInfoList: [], // 总的数据
      data: 0,
      visible: false,
      isDelOne: true,
      id: "",
      num: 0,
    };
  },
  components: { Dialog },
  mounted() {
    this.getList();
  },
  computed: {
    // 全选
    checkAll: {
      get() {
        return (
          this.cartInfoList.every((item) => item.isChecked === 1) &&
          this.cartInfoList.length !== 0
        );
      },
      async set(val) {
        let isChecked = val ? 1 : 0;
        let list = [];
        this.cartInfoList.forEach((item) => {
          item.isChecked = isChecked;
          list.push(item.skuId);
        });
        await updateCheckedAll(isChecked, list);
      },
    },

    // 总价
    totalPrice() {
      return this.cartInfoList.reduce(
        (a, b) => a + b.isChecked * b.skuPrice * b.skuNum,
        0
      );
    },
    // 总数
    totalNo() {
      return this.cartInfoList.reduce((a, b) => a + b.isChecked, 0);
    },
  },
  methods: {
    // 获取购物车数据
    async getList() {
      const result = await reqGetCartList();
      if (result.code === 200) {
        this.cartInfoList = result.data[0].cartInfoList;
      } else {
        console.log("获取数据失败");
      }
    },

    // 修改数量
    async modifyNum(type, item, e) {
      switch (type) {
        case "jia":
          if (item.skuNum < 200) {
            this.num++;
            item.skuNum++;
          }
          break;
        case "jian":
          this.num--;
          item.skuNum--;
          if (item.skuNum < 1) {
            this.num = 0;
            item.skuNum = 1;
          }
          break;
        case "gai":
          let value = e.target.value;
          console.log(value);
          if (skuNumReg.test(value)) {
            this.num = value - item.skuNum;
            item.skuNum = value;
            if (value > 200) {
              item.skuNum = 200;
              this.num = 200 - item.skuNum;
            }
          } else {
            e.target.value = item.skuNum;
          }
          break;
      }
      if (this.timerId) clearTimeout(this.timerId);
      this.timerId = setTimeout(async () => {
        if (this.num == 0) return;
        const result = await reqAddUpdateCart(item.skuId, this.num);
        if (result.code == 200) {
          this.num = 0;
        }
      }, 1000);
    },

    // 单个删除弹出框展示
    deleteSingle(id) {
      this.visible = true;
      this.id = id;
    },
    // 批量删除弹出框展示
    batchDelete() {
      this.isDelOne = false;
      this.visible = true;
    },
    // 单个删除/批量删除
    async delShopCartInfo() {
      if (this.isDelOne) {
        // 单个删除
        const result = await checkDeleteCart(this.id);
        if (result.code == 200) {
          this.cartInfoList = this.cartInfoList.filter(
            (item) => item.skuId !== this.id
          );
          this.visible = false;
          this.$message({
            message: "删除成功",
            type: "success",
          });
        } else {
          this.$message.error("删除失败");
        }
      } else {
        // 批量删除
        const list = [];
        this.cartInfoList.forEach((item) => {
          if (item.isChecked) {
            list.push(item.skuId);
          }
        });
        const result = await reqBatchDelete(list);
        if (result.code == 200) {
          this.cartInfoList = this.cartInfoList.filter(
            (item) => item.skuId !== this.id
          );
          this.visible = false;
          this.$message({
            message: "删除成功",
            type: "success",
          });
        } else {
          this.$message.error("删除失败");
        }
      }
    },
    // 单击修改状态
    async updateChecked(item) {
      let isChecked = 1 - item.isChecked;
      const result = await reqUpdateIsChecked(item.skuId, isChecked);
      if (result.code == 200) {
        item.isChecked = isChecked;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      & > div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        & > li {
          float: left;
        }

        .cart-list-con1 {
          width: 15%;
        }

        .cart-list-con2 {
          width: 35%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con4 {
          width: 10%;
        }

        .cart-list-con5 {
          width: 17%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
.outer {
  .toolbar {
    position: fixed;
    z-index: 999;
    width: 300px;
    height: 100%;
    background-color: #7a6e6e;
    transition: right 0.3s ease-in-out 0s;
    &.toolbar-out {
      top: 0px;
      right: 0px;
    }
    &.toolbar-wrap {
      top: 0px;
      right: -294px;
    }
    .content {
      position: relative;
      left: 6px;
      width: 294px;
      background-color: bisque;
      height: 100%;
      z-index: 99;
    }
    .but {
      position: relative;
      width: 35px;
      height: 35px;
      line-height: 35px;
      text-align: center;
      margin-bottom: 1px;
      cursor: pointer;
      background-color: #7a6e6e;
      border-radius: 3px 0 0 3px;
      position: absolute;
      top: 0;
      /*right: -6px;*/
      left: -29px;
      &.list {
        background-image: url(./images/list.png);
        background-repeat: no-repeat;
        background-size: cover;
      }
      &.pull-wrap {
        background-image: url(./images/cross.png);
        background-repeat: no-repeat;
        background-size: cover;
      }
    }
    .toolist {
      position: absolute;
      top: 50%;
      left: -29px;
      width: 35px;
      margin-top: -80px;
      /*background-color: cadetblue;*/
      .pull {
        position: relative;
        width: 35px;
        height: 35px;
        line-height: 35px;
        text-align: center;
        margin-bottom: 1px;
        cursor: pointer;
        background-color: #7a6e6e;
        border-radius: 3px 0 0 3px;
        z-index: 66;
        .vip {
          background-image: url(./images/toolbars.png);
          background-position: -88px -175px;
        }
        .cart {
          background-image: url(./images/toolbars.png);
          background-position: -50px 0;
        }
        .follow {
          background-image: url(./images/toolbars.png);
          background-position: -50px -50px;
        }
        .history {
          background-image: url(./images/toolbars.png);
          background-position: -50px -100px;
        }
        .message {
          background-image: url(./images/toolbars.png);
          background-position: -190px -150px;
        }
        .jimi {
          background-image: url(./images/toolbars.png);
          background-position: -50px -150px;
        }
        .top {
          background-image: url(./images/toolbars.png);
          background-position: -50px -250px;
        }

        .tab-text {
          width: 62px;
          height: 35px;
          line-height: 35px;
          color: #fff;
          text-align: center;
          font-family: 微软雅黑;
          position: absolute;
          /*position: relative;*/
          z-index: 1;
          left: 35px;
          top: 0;
          background-color: #7a6e6e;
          border-radius: 3px 0 0 3px;
          font-style: normal;
          -webkit-transition: left 0.3s ease-in-out 0.1s;
          transition: left 0.3s ease-in-out 0.1s;
        }
        .tab-ico {
          display: inline-block;
          position: relative;
          /*background-image: url(img/toolbars.png);*/
          background-color: #7a6e6e;
          border-radius: 3px 0 0 3px;
          z-index: 2;
          width: 35px;
          height: 35px;
        }
      }
    }

    & > .pull {
      position: relative;
      width: 35px;
      height: 35px;
      line-height: 35px;
      text-align: center;
      margin-bottom: 1px;
      cursor: pointer;
      background-color: #7a6e6e;
      border-radius: 3px 0 0 3px;
      z-index: 66;
      .tab-ico {
        display: inline-block;
        position: relative;
        /*background-image: url(img/toolbars.png);*/
        background-color: #7a6e6e;
        border-radius: 3px 0 0 3px;
        z-index: 2;
        width: 35px;
        height: 35px;
      }
      .top {
        background-image: url(./images/toolbars.png);
        background-position: -50px -250px;
      }

      .tab-text {
        width: 62px;
        height: 35px;
        line-height: 35px;
        color: #fff;
        text-align: center;
        font-family: 微软雅黑;
        position: absolute;
        /*position: relative;*/
        z-index: 1;
        left: 35px;
        top: 0;
        background-color: #7a6e6e;
        border-radius: 3px 0 0 3px;
        font-style: normal;
        -webkit-transition: left 0.3s ease-in-out 0.1s;
        transition: left 0.3s ease-in-out 0.1s;
      }
    }
    & > .back {
      position: absolute;
      bottom: 0;
      /*right: -6px;*/
      left: -29px;
      display: inline-block;
      background-image: url(./images/toolbars.png);
    }
  }

  .typeNav {
    border-bottom: 2px solid #e1251b;
    .container {
      width: 1200px;
      margin: 0 auto;
      display: flex;
      .all {
        width: 210px;
        height: 45px;
        background-color: #e1251b;
        line-height: 45px;
        text-align: center;
        color: #fff;
        font-size: 14px;
        font-weight: bold;
      }
      .nav {
        a {
          height: 45px;
          margin: 0 22px;
          line-height: 45px;
          font-size: 16px;
          color: #333;
        }
      }
    }
  }
}

.btn-footer {
  position: absolute;
  right: 16px;
  bottom: 20px;
  .btn {
    width: 70px;
    height: 36px;
    margin-right: 12px;
    cursor: pointer;
    border: none;
    font-size: 14px;
    border-radius: 8%;
    &.btn-cancle {
      border: 1px solid #ccc;
      &:hover {
        background-color: #ecf5ff;
        color: #47a2ff;
      }
    }
    &.btn-primary {
      background-color: #409eff;
      color: #fff;
      &:hover {
        background-color: #66b1ff;
      }
    }
  }
}
</style>